package com.gitee.huanminabc.dynamicdb.poll;

import com.gitee.huanminabc.dynamicdb.common.DynamicDbException;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Field;
import java.util.concurrent.*;
/**
 * @author huanmin
 * @date 2024/11/22
 */

public class ShareContextTaskPollExecutor  extends ThreadPoolTaskExecutor {
    @Override
    protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
        try {
            Class<? extends ThreadPoolTaskExecutor> aClass = super.getClass();
            Field queueCapacity = FieldUtils.getField(aClass, "queueCapacity", true);
            int capacity = (int) FieldUtils.readField(queueCapacity, this, true);
            BlockingQueue<Runnable> queue = createQueue(capacity);
            ShareContextPollExecutor executor = new ShareContextPollExecutor(
                    this.getCorePoolSize(), this.getMaxPoolSize(), this.getKeepAliveSeconds(), TimeUnit.SECONDS, queue, threadFactory, rejectedExecutionHandler);
            Field threadPoolExecutor = FieldUtils.getField(aClass, "threadPoolExecutor", true);
            FieldUtils.writeField(threadPoolExecutor, this, executor, true);
            return executor;
        } catch (IllegalAccessException e) {
            throw new DynamicDbException(e,"ShareContextTaskPollExecutor->初始化线程池失败");
        }


    }
}
